package com.sj.parksdk.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Editable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;

import com.ruffian.library.widget.RTextView;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.core.http.subscriber.TipRequestSubscriber;
import com.sj.parksdk.net.http.MyNetApi;
import com.sj.parksdk.net.http.MyRetorfitApi;
import com.sj.parksdk.net.result.databean.Data_Token;
import com.sj.parksdk.setting.Constans;
import com.sj.parksdk.utils.TokenUtils;
import com.sj.parksdk.utils.Utils;
import com.sj.parksdk.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xhttp2.utils.HttpUtils;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.edittext.materialedittext.MaterialEditText;
import com.xuexiang.xutil.common.StringUtils;

import butterknife.BindView;
import butterknife.OnClick;

@Page(anim = CoreAnim.none, name = "密码登录")
public class FragmentLoginPassword extends BaseFragment {
    @BindView(R2.id.iv_logo)
    AppCompatImageView ivLogo;
    @BindView(R2.id.et_phone_number)
    MaterialEditText etPhoneNumber;
    @BindView(R2.id.et_password)
    MaterialEditText etPassword;
    @BindView(R2.id.btn_login)
    Button btnLogin;
    @BindView(R2.id.tv_other_logintype)
    RTextView tvOtherLogintype;
    @BindView(R2.id.tv_agreement)
    AppCompatTextView tvAgreement;

    @Override
    protected TitleBar initTitle() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_login_password;
    }

    @Override
    protected void initViews() {
        initAgreePrivacy();
        updateConfirmBt(false);
    }

    @Override
    protected void initListeners() {
        TextChange textChange = new TextChange();
        etPassword.addTextChangedListener(textChange);
        etPhoneNumber.addTextChangedListener(textChange);
    }

    private void initAgreePrivacy() {
        tvAgreement.setText(getPrivacyContent(getContext()));
        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
    }

    /**
     * @return 隐私政策说明
     */
    private static SpannableStringBuilder getPrivacyContent(Context context) {
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder()
                .append("登录即代表同意").append(getUserPrivacyLink(context, ResUtils.getString(R.string.login_server_agreement), Constans.API_AGREEMENT))
                .append("和")
                .append(getUserPrivacyLink(context,ResUtils.getString(R.string.login_privacy_agreement), Constans.PRIVACY_AGREEMENT));
        return stringBuilder;
    }

    /**
     * @return
     */
    private static SpannableString getUserPrivacyLink(Context context, String privacyName, String privacyUrl) {
        SpannableString spannableString = new SpannableString(privacyName);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Utils.goWeb(context, privacyUrl);
            }
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
            }
        }, 0, privacyName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    @OnClick({R2.id.btn_login, R2.id.tv_other_logintype})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_login) {
            if (etPhoneNumber.validate() && etPassword.validate()) {
                if (etPassword.getEditValue().length() < 6 || etPassword.getEditValue().length() > 16)
                    etPassword.setError(ResUtils.getString(R.string.tip_password_error));
                else loginByPassword(etPhoneNumber.getEditValue(), etPassword.getEditValue());
            }
        } else if (id == R.id.tv_other_logintype) {
            gotoLoginByCode();
        }
    }

    private void gotoLoginByCode() {
        openPage(LoginFragment.class,false);
    }

    @SuppressLint("CheckResult")
    private void loginByPassword(String phone, String password) {
        MyNetApi.LoginPassword params = new MyNetApi.LoginPassword();
        params.setUsername(phone)
                .setPassword(password)
                .setAppId(Constans.APP_ID)
                .setDeviceId(Constans.DEVICE_TYPE+"123")
                .setDeviceType(Constans.DEVICE_TYPE);
        CustomRequest request = XHttp.custom();
        request.apiCall(request.create(MyRetorfitApi.TokenService.class)
                .login(HttpUtils.getJsonRequestBody(params)))
                .subscribeWith(new TipRequestSubscriber<Data_Token>() {
                    @Override
                    protected void onSuccess(Data_Token data) {
                        LoginSuccess(data);
                    }
                });
    }

    private void LoginSuccess(Data_Token data) {
        if (TokenUtils.handleLoginSuccess(data))  popToBack();
        else XToastUtils.error("登录失败");
    }

    private class TextChange implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }
        @Override
        public void afterTextChanged(Editable s) {
            boolean a = !StringUtils.isEmpty(etPhoneNumber.getEditValue().trim());
            boolean b =  !StringUtils.isEmpty(etPassword.getEditValue().trim());
            updateConfirmBt(b && a);
        }
    }

    private void updateConfirmBt(boolean b) {
        btnLogin.setBackground(ResUtils.getDrawable(b?R.drawable.park_selector_bg_loginbt_normal :R.drawable.park_shap_bg_loginbt_enable));
    }
}
